package Json2RDF.Surface2RDF.SurfaceWriter;

import Json2RDF.Json2Java.OntologyClasses.Edge;
import Json2RDF.Surface2RDF.IndexTable.EdgeId2ResourceIndexTable;
import RDFManager.PropertySet;
import RDFManager.RDFHead;
import RDFManager.RDFReader;
import RDFManager.ResourceSet;

import java.util.List;
import java.util.stream.IntStream;

import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDF;

/**
 * {@code EdgeWriter}类提供将edge写入RDF文件的方法
 */
public class EdgeWriter {

  /**
   * 遍历List中的每个{@code Edge}类对象，将对应数据属性值写入RDF文件，并将该边写入{@link EdgeId2ResourceIndexTable#edgeResourceIdxTbl edgeMap}
   *
   * @param edgeList 待写入的edge列表
   */
  public static void writeList(List<Edge> edgeList) {

    IntStream.range(0, edgeList.size()).forEach(i -> {
      write(edgeList.get(i), "edge" + (i + 1));
      EdgeId2ResourceIndexTable.edgeResourceIdxTbl.computeIfAbsent(edgeList.get(i).getID(), v -> RDFReader.model.getResource(RDFHead.namespace + "edge" + (i + 1)));
    });
  }


  private static void write(Edge edge, String localName) {
    Resource inst = RDFReader.model.createResource(RDFHead.namespace + localName);
    RDFReader.model.add(inst, RDF.type, ResourceSet.edge);
    inst.addLiteral(PropertySet.hasID, edge.getID());
    RDFTripleArrayWriter.writeTripleArray(inst, "hasEnd1", edge.getEnd1());
    RDFTripleArrayWriter.writeTripleArray(inst, "hasEnd2", edge.getEnd2());
    if (!isZeroArray(edge.getDirectionVector())) {
      RDFTripleArrayWriter.writeTripleArray(inst, "hasDirectionVector", edge.getDirectionVector());
    }
  }

  private static boolean isZeroArray(double[] array){
    if (array !=null && array.length == 2){
      return array[0] == 0 && array[1] == 0;
    }
    return false;
  }
}
